package cn.shyouchi.wuguanjia.android.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;

import com.trello.rxlifecycle.android.ActivityEvent;

import cn.shyouchi.wuguanjia.android.utils.ResourceUtil;
import cn.shyouchi.wuguanjia.android.utils.StatusBarUtil;
import rx.subjects.PublishSubject;

/**
 * Created by Eenie on 2016/10/12 at 15:01
 * Des:
 */

public abstract class BaseActivity extends AppCompatActivity {

    protected Context mContext;

    protected final PublishSubject<ActivityEvent> mLifecycleSubject = PublishSubject.create();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mLifecycleSubject.onNext(ActivityEvent.CREATE);

        initTheme();
        super.onCreate(savedInstanceState);
        setContentView(initContentView());
        mContext = this;
        setTranslucentStatus(isApplyStatusBarTranslucency());
        setStatusBarColor(isApplyStatusBarColor());
        initInjector();
        initUiAndListener();
    }


    @Override
    protected void onResume() {
        mLifecycleSubject.onNext(ActivityEvent.RESUME);
        super.onResume();

    }

    @Override
    protected void onPause() {
        mLifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();

    }

    private void initTheme() {
        int theme;
        try {
            theme = getPackageManager().getActivityInfo(getComponentName(), 0).theme;
        } catch (PackageManager.NameNotFoundException e) {
            return;
        }
//        if (theme != R.style.AppThemeLaunch) {
//            theme = ThemeUtil.themeArr[SettingPrefUtil.getThemeIndex(this)][
//                    SettingPrefUtil.getNightModel(this) ? 1 : 0];
//        }
        setTheme(theme);
    }

    /**
     * 设置Layout 如 R.layout.main_layout
     */
    public abstract int initContentView();

    /**
     * 注入Injector
     */
    public abstract void initInjector();

    /**
     * init UI && Listener
     */
    public abstract void initUiAndListener();

    /**
     * is applyStatusBarTranslucency
     */
    protected abstract boolean isApplyStatusBarTranslucency();

    /**
     * set status bar translucency
     */
    protected void setTranslucentStatus(boolean on) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if (on) {
                winParams.flags |= bits;
            } else {
                winParams.flags &= ~bits;
            }
            win.setAttributes(winParams);
        }
    }

    protected abstract boolean isApplyStatusBarColor();

    /**
     * use SystemBarTintManager
     */
    public void setStatusBarColor(boolean on) {
        if (on) {
            StatusBarUtil.setColor(this, ResourceUtil.getThemeColor(this), 0);
        }
    }

    /**
     * 重载Activity
     */
    public void reload() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        return ResourceUtil.getStatusBarHeight(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (getSupportParentActivityIntent() != null) {
                startActivity(getSupportParentActivityIntent());
            }
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        mLifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        mLifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }


//    public static void fixInputMethodManagerLeak(Context destContext) {
//        if (destContext == null) {
//            return;
//        }
//
//        InputMethodManager imm = (InputMethodManager) KDApplication.getInstance()
//                .getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (imm == null) {
//            return;
//        }
//
//        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
//        Field f = null;
//        Object obj_get = null;
//        for (int i = 0; i < arr.length; i++) {
//            String param = arr[i];
//            try {
//                f = imm.getClass().getDeclaredField(param);
//                if (f.isAccessible() == false) {
//                    f.setAccessible(true);
//                } // author: sodino mail:sodino@qq.com
//                obj_get = f.get(imm);
//                if (obj_get != null && obj_get instanceof View) {
//                    View v_get = (View) obj_get;
//                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
//                        f.set(imm, null); // 置空，破坏掉path to gc节点
//                    } else {
//                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
////                        if (QLog.isColorLevel()) {
////                            QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
////                        }
//                        break;
//                    }
//                }
//            } catch (Throwable t) {
//                t.printStackTrace();
//            }
//        }
//    }


}
